<template>
  <view class="content">
    <view
      class="title"
      style="display: flex"
    >
      欢迎进入首页
      <view v-if="Object.keys(user).length !==0"></view>
      uid：{{ user._id ? user._id : '获取中' }}
    </view>
    <view class="userStatus">
      {{ isLogin ? '用户已经登录' : ' 用户未登录' }}
    </view>
  </view>
</template>

<script>
const xyUserCo = uniCloud.importObject('xy-user-co') //请出我们后端的云对象
export default {
  data() {
    return {
      isLogin: false,
      user: {}
    }
  },
  onLoad() {
    //前端判断用户是否登录 就判断缓存中是否有 token
    let token = uni.getStorageSync('token')
    if (token) {
      this.isLogin = true
      this.user = uni.getStorageSync('user')
      this.user._id = this.user._id.slice(0, 6)
    } else {
      // 没有 token 不要怕 去后端拿
      uni
        .login()
        .then(({ code }) => {
          return xyUserCo.loginWithMp(code)
        })
        .then(res => {
          console.log('res: ', res)
          //拿到 token 刷新缓存和登录状态
          uni.setStorageSync('token', res.token)
          uni.setStorageSync('user', res.user)
          this.isLogin = true
          this.user = res.user
          this.user._id = this.user._id.slice(0, 6)
        })
    }
  },
  methods: {}
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
